<?php

use app\modules\Admin\models\membertransferlogModel;
use Illuminate\Database\Capsule\Manager as DB;
#[用户转帐记录管理]
class TransfermanageController extends AcommonController
{
    public function init() {
        $this->model = new membertransferlogModel();
        $this->table = 'member_transfer_log';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[用户转帐记录列表]
    public function indexAction($returnData = FALSE)
    {
        if($this->isPost()){
            $this->model = $this->model->with(['getMember'=>function($withQuery){
                $withQuery->withTrashed();
            }, 'getTarget'=>function($withQuery){
                $withQuery->withTrashed();
            }]);
            $post_data = $this->postData;
            $search_data = [];
            $WalletTypeArray = [
                'money' => 'money',
                'score' => 'score',
            ];
            if(isset($post_data['type']) && !empty($post_data['type']) && in_array($post_data['type'], $WalletTypeArray)){
                array_push($search_data, ['wallet_type', '=', $post_data['type']]);
            }
            if(isset($post_data['transfer_start']) && !empty($post_data['transfer_start'])){
                $this->model = $this->model->whereDate('created_at', '>=', $post_data['transfer_start']);
            }
            if(isset($post_data['transfer_end']) && !empty($post_data['transfer_end'])){
                $this->model = $this->model->whereDate('created_at', '<=', $post_data['transfer_end']);
            }
            $keywordsTypeArray = [
                'user_id' => 'user_id',
                'user_phone' => 'user_phone',
                'target_id' => 'target_id',
                'target_phone' => 'target_phone',
            ];
            if(isset($post_data['keywordsType']) && isset($post_data['keywords'])
                && in_array($post_data['keywordsType'], $keywordsTypeArray)
                && !empty($post_data['keywords'])){
                if($post_data['keywordsType'] == $keywordsTypeArray['user_id'] && intval($post_data['keywords']) > 0){
                    array_push($search_data, ['member_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['target_id'] && intval($post_data['keywords']) > 0){
                    array_push($search_data, ['target_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['user_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($search_data, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['member_id', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['target_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($search_data, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['target_id', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
            }
            unset($keywordsTypeArray);
            $this->search = $search_data;
            return parent::indexAction($returnData); // TODO: Change the autogenerated stub
        }else{
            $this->_view->assign('is_dialog', $this->get('dialog', 0));
            $this->_view->assign('default_type', $this->get('type', 'all'));
            $this->_view->assign('default_keywords_type', $this->get('keywordsType', 'user_id'));
            $this->_view->assign('default_keywords', $this->get('keywords', ''));
            $this->_view->display( strtolower($this->controller) . '/index.html');
        }
    }

    #[转帐记录导出]
    public function exportAction()
    {
        $type     = $this->get('keywordsType');
        $keywords = $this->get('keywords');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $mode = $this->get('mode');

        $dirpath = APP_PATH . '/public/excel/';
        if ($dirpath !== '.' && !file_exists($dirpath)) {
            mkdir($dirpath, 0777, true);
        }
        $filename = 'WalletTransfer' . date('Ymd') . uniqid() . '.xlsx';
        $filepath = $dirpath . $filename;
        $res = exec("php ". APP_PATH . "/public/cli.php export/wallettransfer \"mode={$mode}&type={$type}&keywords={$keywords}&start_on={$startOn}&end_on={$endOn}&path={$filepath}\"");
        if ($res === 'Done' && file_exists($dirpath . $filename)) {
            if( $webpath = syncFile($filepath) ){
                ret(0, '用户转帐记录导出excel成功', $webpath);
            }
        }
        ret(30003, '用户转帐记录导出失败');
    }

    #[转帐统计]
    public function statisticsAction()
    {
        $rollType = membertransferlogModel::getRollType();
        $walletType = array_merge(['all' => '全部'], membertransferlogModel::getWalletType());
        $modeArray = [
            'all' => '全部',
            'today' => '今天',
            'yesterday' => '昨天',
            'thisweek' => '本周',
            'lastweek' => '上周',
            'thismonth' => '本月',
            'lastmonth' => '上月',
            'other' => '自定义'
        ];
        $actionArray = array_keys($rollType);
        $action = in_array($this->get('roll_type'), $actionArray)?$this->get('roll_type'):'rollout';
        if($this->isPost()){
            $groupByArray = ['member_id'];
            if($action === 'rollout'){
                $this->model = membertransferlogModel::query()
                    ->with(['getMember'=>function($withQuery){
                        $withQuery->withTrashed();
                    }])
                    ->select(['id','member_id','wallet','wallet_type']);
            }else{
                $this->model = membertransferlogModel::query()
                    ->with(['getTarget'=>function($withQuery){
                        $withQuery->withTrashed();
                    }])
                    ->select(['id','target_id','wallet','wallet_type']);
                $groupByArray = ['target_id'];
            }
            $this->model = $this->model->addSelect(DB::Raw("SUM(wallet) as total_trans"))
                ->addSelect(DB::Raw("COUNT(id) as trans_num"));
            $post_data = $this->postData;
            $WalletTypeArray = array_keys($walletType);
            $post_data['type'] = in_array($post_data['type'], $WalletTypeArray)?$post_data['type']:$WalletTypeArray[0];
            if($post_data['type'] !== 'all'){
                $this->model = $this->model->where('wallet_type', '=', $post_data['type']);
            }else{
                array_unshift($groupByArray, 'wallet_type');
            }
            if(count($groupByArray)){
                $this->model = $this->model->groupBy($groupByArray);
            }
            $mode_array = array_keys($modeArray);
            $mode = in_array($post_data['mode'], $mode_array)?$post_data['mode']:'all';
            $startOn = '';
            $endOn = '';
            $operator = 'between';
            switch ($mode){
                case 'today':
                    $startOn = carbon()->today()->format('Y-m-d');
                    $operator = 'eq';
                    break;
                case 'thisweek':
                    $startOn = carbon()->startOfWeek()->format('Y-m-d');
                    break;
                case 'yesterday':
                    $startOn = carbon()->yesterday()->format('Y-m-d');
                    $operator = 'eq';
                    break;
                case 'lastweek':
                    $startOn = carbon()->subDays(7)->startOfWeek()->format('Y-m-d');
                    $endOn = carbon()->subDays(7)->endOfWeek()->format('Y-m-d');
                    break;
                case 'thismonth':
                    $startOn = carbon()->startOfMonth()->format('Y-m-d');
                    break;
                case 'lastmonth':
                    $startOn = carbon()->subMonth()->startOfMonth()->format('Y-m-d');
                    $endOn =  carbon()->subMonth()->endOfMonth()->format('Y-m-d');
                    break;
                case 'other':
                    if(isset($post_data['transfer_start']) && !empty($post_data['transfer_start'])){
                        $startOn = $post_data['transfer_start'];
                    }
                    if(isset($post_data['transfer_end']) && !empty($post_data['transfer_end'])){
                        $endOn = $post_data['transfer_end'];
                    }
                    break;
            }
            if(!empty($startOn)){
                if($operator === 'between'){
                    $this->model = $this->model->whereDate('created_at', '>=', $startOn);
                }else{
                    $this->model = $this->model->whereDate('created_at', '=', $startOn);
                }
            }
            if(!empty($endOn)){
                $this->model = $this->model->whereDate('created_at', '<=', $endOn);
            }
            $countQuery = clone $this->model;
            $count_sql = $countQuery->toSql();
            $total = DB::table(DB::Raw("($count_sql) as count"))->mergeBindings($countQuery->getQuery())->count(['id']);
            $sort = $this->get('sort', 'id');
            $order = $this->get('order', 'desc');
            $query = $this->model->orderBy($sort, $order)->orderBy($this->primaryKey, 'DESC');
            $page = $this->get('page', 1);
            if (!empty($page)) {
                $limit = $this->get('rows', 10);
                $offset = ($page - 1) * $limit;
                $query = $query->offset($offset)->limit($limit);
            }
            $rows = $query->get();
            unset($mode_array, $mode, $modeArray, $WalletTypeArray, $walletType, $rollType, $actionArray, $action, $post_data, $sort, $order, $page, $limit, $offset, $query);
            json(['total' => $total, 'rows' => $rows]);
        }else{
            $this->_view->assign('mode_list', json_encode($modeArray));
            $this->_view->assign('roll_type', json_encode($rollType));
            $this->_view->assign('wallet_type', json_encode($walletType));
            if($action === 'rollout'){
                $this->_view->display( strtolower($this->controller) . '/statistics.html');
            }else{
                $this->_view->display( strtolower($this->controller) . '/statistics_in.html');
            }
        }

    }

    #[转帐统计导出]
    public function exportstatisticsAction()
    {
        $type     = $this->get('type');
        $rollType = $this->get('roll_type');
        $startOn = $this->get('start_on');
        $endOn = $this->get('end_on');
        $mode = $this->get('mode');
        $dirpath = APP_PATH . '/public/excel/';
        if ($dirpath !== '.' && !file_exists($dirpath)) {
            mkdir($dirpath, 0777, true);
        }
        if($rollType === 'rollout'){
            $filename_t = 'WalletTransferOutStatistics';
        }else{
            $filename_t = 'WalletTransferInStatistics';
        }
        $filename = $filename_t . date('Ymd') . uniqid() . '.xlsx';
        $filepath = $dirpath . $filename;
        $res = exec("php ". APP_PATH . "/public/cli.php export/wallettransferstatistics \"mode={$mode}&type={$type}&roll_type={$rollType}&start_on={$startOn}&end_on={$endOn}&path={$filepath}\"");
        if ($res === 'Done' && file_exists($dirpath . $filename)) {
            if( $webpath = syncFile($filepath) ){
                ret(0, '用户转帐统计导出excel成功', $webpath);
            }
        }
        ret(30003, '用户转帐统计导出失败');
    }
}